<template>
  <a-page-header>
    <a-card>
      <a-table :columns="columns" :data-source="data"
               :loading="loading" :scroll="{ x: 2000}"
               :rowKey="record => record.movieId" >
        <template slot="title">
          <a-row type="flex" justify="space-between">
            <a-col :span="4">
              <a-button type="primary" style="margin-left: 10px;" icon="plus-circle" @click="showAddModal()" >
                新增电影
              </a-button>
              <!--       增加与修改的表单 Start       -->
              <a-modal
                  :title="modalForm.title"
                  :visible="modalForm.visible"
                  :confirm-loading="modalForm.confirmLoading"
                  okText="提交"
                  cancelText="取消"
                  @ok="handleModalOk"
                  @cancel="handleModalCancel">
                <a-form-model @submit="handleModalFormSubmit"
                              :label-col="{span:4}" :wrapper-col="{span:14}" ref="addForm"
                              :model="addForm" :rules="modalForm.modalFormRules"  >

                  <a-form-model-item label="电影名称" ref="movieName" prop="movieName">
                    <a-input v-model="addForm.movieName" placeholder="电影名称"/>
                  </a-form-model-item>
                  <a-form-model-item label="电影演员" ref="actor" prop="actor">
                    <a-input v-model="addForm.actor" placeholder="电影演员"/>
                  </a-form-model-item>
                  <a-form-model-item label="电影摘要" ref="abs" prop="abs">
                    <a-input v-model="addForm.abs" placeholder="电影摘要"/>
                  </a-form-model-item>
                  <a-form-model-item label="电影地区" ref="area" prop="area">
                    <a-select
                        mode="multiple"
                        placeholder="电影地区"
                        v-model="addForm.area"
                        style="width: 100%"
                        @change="handleAreaChange"
                    >
                      <a-select-option v-for="item in this.allAreaItems" :key="item.paramKey" :value="item.paramKey">
                        {{ item.paramValue }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                  <a-form-model-item label="电影类型" ref="type" prop="type">
                    <a-select
                        mode="multiple"
                        placeholder="电影地区"
                        v-model="addForm.type"
                        style="width: 100%"
                        @change="handleTypeChange"
                    >
                      <a-select-option v-for="item in this.allTypeItems" :key="item.paramKey" :value="item.paramKey">
                        {{ item.paramValue }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>

                  <a-form-model-item label="导演" ref="director" prop="director">
                    <a-input v-model="addForm.director" placeholder="导演"/>
                  </a-form-model-item>
                  <a-form-model-item label="电影描述" ref="movieInfo" prop="movieInfo">
                    <a-input v-model="addForm.movieInfo" placeholder="电影描述"/>
                  </a-form-model-item>
                  <a-form-model-item label="上映时间" ref="showTime" prop="showTime">
                    <a-date-picker
                        v-model="addForm.showTime"
                        show-time
                        type="date"
                        valueFormat="YYYY-MM-DD HH:mm:ss"
                        placeholder="上映时间"
                        style="width: 100%;"
                    />
                  </a-form-model-item>
                  <a-form-model-item label="电影语言" ref="language" prop="language">
                    <a-select
                        placeholder="电影语言"
                        v-model="addForm.language"
                        style="width: 100%">
                      <a-select-option value="国语">
                        国语
                      </a-select-option>
                      <a-select-option value="英语">
                        英语
                      </a-select-option>
                      <a-select-option value="日语">
                        日语
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>


                  <a-form-model-item label="电影时长" ref="time" prop="time">
                    <a-input-number v-model="addForm.time" placeholder="电影时长" style="width: 100%;"/>
                  </a-form-model-item>
                  <a-form-model-item label="照片路径" ref="imgPath" prop="imgPath">
                    <a-input v-model="addForm.imgPath" placeholder="照片路径"/>
                  </a-form-model-item>
                  <a-form-model-item label="视频路径" ref="video" prop="video">
                    <a-input v-model="addForm.video" placeholder="视频路径"/>
                  </a-form-model-item>
                  <a-form-model-item label="是否启用" ref="status" prop="status">
                    <a-radio-group v-model="addForm.status">
                      <a-radio-button value="1">
                        启用
                      </a-radio-button>
                      <a-radio-button value="0">
                        禁用
                      </a-radio-button>
                    </a-radio-group>
                  </a-form-model-item>
                </a-form-model>

              </a-modal>
              <!--       end       -->
            </a-col>

            <a-col >
              <!--       表头查询表单       -->
              <a-form-model ref="queryForm"
                            layout="inline" :model="formInline">
                <a-form-model-item ref="movieNameLike" prop="movieNameLike">
                  <a-input v-model="formInline.movieNameLike" placeholder="模糊查询电影名称">
                  </a-input>
                </a-form-model-item>

                <a-form-model-item>
                  <a-button
                      type="primary"
                      @click="handleSubmit">
                    查询
                  </a-button>
                  <a-button style="margin-left: 10px;" @click="resetSearchForm('queryForm')">
                    重置
                  </a-button>
                </a-form-model-item>
              </a-form-model>
              <!--       表头查询表单  end     -->
            </a-col>
          </a-row>
        </template>
        <template #movieArea="movieArea">
          <a-tag :key="item" :color="'pink'" v-for="item in movieArea.split('/')">
            {{getAreaValue(item)}}
          </a-tag>
        </template>
        <template #movieType="movieType">
          <a-tag :key="item" :color="'purple'" v-for="item in movieType.split('/')">
            {{getTypeValue(item)}}
          </a-tag>
        </template>

        <template #status="status">
          <a-tag :color="status?'green':'volcano'">
            <span v-if="status">启用</span>
            <span v-else>禁用</span>
          </a-tag>
        </template>

        <template #action="record">
          <a-button type="primary" shape="circle" icon="edit" @click="showEditModal(record)" />
          <a-divider type="vertical" />
          <a-popconfirm
              :title="`确认要删除:${record.movieName}吗?`"
              ok-text="确认"
              cancel-text="取消"
              @confirm="handleDeleteMovie(record.movieId)"
          >
            <a-icon slot="icon" type="question-circle-o" style="color: red" />
            <a-button type="danger" shape="circle" icon="delete" />
          </a-popconfirm>
          <a-divider type="vertical" />
          <a-button type="primary" shape="circle" icon="upload" @click="showUpload(record)" />
        </template>
      </a-table>
<!--   图片文件上传   -->
      <a-modal
          :key="'uploadModal'"
          :title="uploadModal.title"
          :visible="uploadModal.visible"
          @cancel="handleMovieCancel"
          :footer="null">

        <a-tabs v-model="uploadModal.headers.type"
                :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
                @change="handleTabClick">
          <a-tab-pane key="img" tab="图片上传">
            <a-upload-dragger
                :key="'uploadImg'+new Date().getTime()"
                name="file"
                :multiple="true"
                list-type="picture"
                :before-upload="beforeUpload"
                action="http://127.0.0.1:8080/movie/uploadMovieRes"
                :headers="uploadModal.headers"
                :default-file-list="fileList"
                :remove="removeMovie"
                @change="handleUploadChange"
            >
              <p class="ant-upload-drag-icon">
                <a-icon type="inbox" />
              </p>
              <p class="ant-upload-text">
                Click or drag file to this area to upload
              </p>
              <p class="ant-upload-hint">
                Support for a single or bulk upload. Strictly prohibit from uploading company data or other
                band files
              </p>
            </a-upload-dragger>
          </a-tab-pane>
          <a-tab-pane key="video" tab="视频上传">
            <a-upload-dragger
                :key="'uploadVideo'+new Date().getTime()"
                name="file"
                :multiple="true"
                list-type="picture"
                action="http://192.168.0.106:8080/movie/uploadMovieRes"
                :headers="uploadModal.headers"
                :default-file-list="fileListVideo"
                :remove="removeMovie"
                @change="handleUploadChange"
            >
              <p class="ant-upload-drag-icon">
                <a-icon type="inbox" />
              </p>
              <p class="ant-upload-text">
                Click or drag file to this area to upload
              </p>
              <p class="ant-upload-hint">
                Support for a single or bulk upload. Strictly prohibit from uploading company data or other
                band files
              </p>
            </a-upload-dragger>
          </a-tab-pane>
        </a-tabs>



      </a-modal>
    </a-card>
  </a-page-header>
</template>

<script>
import {
  addMovie,
  updateMovie,
  deleteMovieById,
  getAllMovie,
  findAllMovieType,
  findMovieArea,
  findMoviePicList,
  deleteMoviePic, queryMovieLike
} from "@/api/movie";
import {getJwtToken} from "@/lib/utils/TokenUtil";
import axios from "axios";

const columns = [
  {
    title: '电影标识',
    dataIndex: 'movieId',
    key: 'movieId',
    fixed: 'left',
    width: 90
  },
  {
    title: '电影名称',
    dataIndex: 'movieName',
    key: 'movieName',
    fixed: 'left',
    width: 110
  },
  {
    title: '演员',
    dataIndex: 'actor',
    key: 'actor',
    ellipsis: true,
    width: 150
  },
  {
    title: '语言',
    dataIndex: 'language',
    key: 'language',
    ellipsis: true,
    width: 150
  },
  {
    title: '电影摘要',
    dataIndex: 'abs',
    key: 'abs',
    ellipsis: true,
    width: 150
  },
  {
    title: '电影地区',
    dataIndex: 'area',
    key: 'area',
    width: 200,
    scopedSlots: { customRender: 'movieArea' },
  },
  {
    title: '电影类型',
    dataIndex: 'type',
    key: 'type',
    width: 180,
    scopedSlots: { customRender: 'movieType' },
  },
  {
    title: '导演',
    dataIndex: 'director',
    key: 'director',
    ellipsis: true,
    width: 150
  },
  {
    title: '照片路径',
    dataIndex: 'imgPath',
    key: 'imgPath',
    ellipsis: true,
    width: 150
  },
  {
    title: '视频路径',
    dataIndex: 'video',
    key: 'video',
    ellipsis: true,
    width: 150
  },
  {
    title: '评分',
    dataIndex: 'rate',
    key: 'rate',
    width: 90
  },
  {
    title: '评价人数',
    dataIndex: 'rateCount',
    key: 'rateCount',
    width: 90
  },
  {
    title: '上映时间',
    dataIndex: 'showTime',
    key: 'showTime',
    ellipsis: true,
    width: 150
  },
  {
    title: '电影时长',
    dataIndex: 'time',
    key: 'time',
    width: 90
  },
  {
    title: '票房',
    dataIndex: 'totalMoney',
    key: 'totalMoney',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 90,
    scopedSlots: { customRender: 'status' },
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width:180,
    scopedSlots: { customRender: 'action' },
  }
];

const modalFormRules = {
  movieName: [
    {required: true, message: '请输入电影名称', trigger: ['blur']},
  ],
  status:[
    {required: true, message: '请选择是否启用', trigger: 'change'}
  ]
}
export default {
  name: "SystemMovie",
  data() {
    return {
      formInline: {
        movieNameLike: '',
        searchStatus: undefined,
      },
      uploadModal:{
        customActiveKey:'uploadImg',
        title:'',
        visible:false,
        headers:{
          AccessToken:getJwtToken(),
          movieId:undefined,
          type:"img"
        }
      },
      modalForm:{
        title:'',
        visible:false,
        confirmLoading: false,
        modalFormRules,
        isDisabled:false
      },
      addForm:{
        movieId:undefined,
        movieName:'',
        actor:'',
        abs:'',
        area:[],
        type:[],
        director:'',
        movieInfo:'',
        language:'',
        imgPath:'',
        picture:'',
        video:'',
        rate:'',
        showTime:undefined,
        time:undefined,
        status:undefined,
      },
      allTypeItems:[],
      allAreaItems:[],
      fileList:[],
      fileListVideo:[],
      data:[],
      loading:false,
      columns,
      isHandleSubmit:false,
    }
  },
  beforeRouteEnter (to,from,next) {
    axios.all([findMovieArea(),findAllMovieType()])
        .then(axios.spread(function (res1, res2){
          next(vm =>vm.setAllItems(res1.data,res2.data))
        }))
  },
  mounted() {
    this.getMovieData()
  },
  methods:{
    setAllItems(area,type){
      this.allAreaItems=area
      this.allTypeItems=type
    },
    handleAreaChange(selectedItems) {
      this.addForm.area = selectedItems;
    },
    handleTypeChange(selectedItems) {
      this.addForm.type = selectedItems;
    },
    // 查询表单提交
    print(a,b){
      console.log(a,b)
    },
    handleSubmit() {
      console.log(this.formInline)
      console.log('SystemMovie handleSubmit',this.formInline.movieNameLike)
      queryMovieLike(this.formInline.movieNameLike).then(res=>{
        this.data = res.data
      })

    },
    resetSearchForm(formName) {
      this.$refs[formName].resetFields();
      if (this.isHandleSubmit){
        this.getMovieData()
      }
    },
    // 获取电影列表数据
    getMovieData(){
      this.loading = true
      getAllMovie().then(res=>{
        this.data = res.data
      }).catch(err=>{
        console.log("SystemMovie:getMovieData:"+err.message);
      }).finally(()=>{
        this.loading = false
      })
    },
    // addForm start
    showAddModal(){
      this.modalForm.isDisabled = false;
      this.modalForm.visible =  true
      this.modalForm.title = '新增电影'
    },
    showEditModal(record){
      console.log(record)
      let {movieId, movieName, actor, status,abs,area,type,director,movieInfo,
        language,imgPath,video,showTime,time} = record
      let tranArea = area.split("/")
      let tranType = type.split("/")
      this.addForm = {
        movieId, movieName, actor,abs,director,movieInfo,language,imgPath,video,showTime,time,
        area: tranArea,
        type: tranType,
        status: status?"1":"0"
      }
      this.modalForm.isDisabled = true
      this.modalForm.visible =  true
      this.modalForm.title = '修改电影'

    },
    //文件上传
    showUpload(record){
      this.uploadModal.headers.movieId = record.movieId
      this.uploadModal.title = '电影资源上传与管理'
      let _this = this
      findMoviePicList(record.movieId,this.uploadModal.headers.type)
      .then(res=>{
        if (_this.uploadModal.headers.type==='img'){
          _this.fileList = res.data
        }else if (_this.uploadModal.headers.type==='video'){
          _this.fileListVideo= res.data
        }
        _this.uploadModal.visible =  true
      })
    },
    handleMovieCancel(){
      this.uploadModal.visible =  false
    },
    // 状态有：uploading done error removed
    handleUploadChange(info) {
      let status = info.file.status;
      let  res;
      if (status !== 'uploading'&&status!=='removed') {
        console.log(info.file, info.fileList);
        res = info.file.response
        if (status === 'done'&&res.result) {
          this.$message.success(`${info.file.name} 文件上传成功.`);
        } else if (status === 'error'||!res.result) {
          this.$message.error(`${info.file.name} 文件上传失败.`);
        }
        findMoviePicList(this.uploadModal.headers.movieId,this.uploadModal.headers.type)
            .then(res=>{
              if (this.uploadModal.headers.type==='img'){
                this.fileList = res.data
              }else if (this.uploadModal.headers.type==='video'){
                this.fileListVideo= res.data
              }
            })
      }
    },
    // 文件上传前置处理
    beforeUpload(file) {
      // const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      // if (!isJpgOrPng) {
      //   this.$message.error('You can only upload JPG file!');
      // }
      const isLt2M = file.size / 1024 / 1024 < 4;
      if (!isLt2M) {
        this.$message.error('图片大小必须小于4MB!');
      }
      // return isJpgOrPng && isLt2M;
      return isLt2M;
    },
    // 删除已上传的电影资源
    removeMovie(file){
      console.log(file)
      deleteMoviePic(this.uploadModal.headers.movieId,file.name,this.uploadModal.headers.type)
      .then(res=>{
        return res.result
      }).catch(()=>{
        return false;
      })
    },
    // 上传类型切换
    handleTabClick(){
      findMoviePicList(this.uploadModal.headers.movieId,this.uploadModal.headers.type)
          .then(res=>{
            if (this.uploadModal.headers.type==='img'){
              this.fileList = res.data
            }else if (this.uploadModal.headers.type==='video'){
              this.fileListVideo= res.data
            }
          })
    },
    // 处理modal里的表单提交
    handleModalOk(){
      this.handleModalFormSubmit()
    },
    handleModalCancel(){
      this.modalForm.visible = false
      this.resetForm('addForm')
    },
    handleModalFormSubmit(){
      this.$refs['addForm'].validate(valid=>{
        if (valid) {
          let submitData = this.addForm
          submitData.status = this.addForm.status === "1"
          delete  submitData.allAreaItems
          delete  submitData.allTypeItems
          submitData.area = this.addForm.area.join("/")
          submitData.type = this.addForm.type.join("/")
          this.modalForm.confirmLoading = true
          if (this.modalForm.isDisabled){
            this.handleUpdateMovie(submitData)
          }else {
            this.handleAddMovie(submitData)
          }
        } else {
          this.handleFiled(new Error('表单校验不通过'))
          return false;
        }
      })
    },
    resetForm(formName) {
      this.addForm = {
            movieId:undefined,
            movieName:'',
            actor:'',
            abs:'',
            area:[],
            type:[],
            director:'',
            movieInfo:'',
            language:'',
            imgPath:'',
            video:'',
            rate:'',
            showTime:undefined,
            time:'',
            status:undefined
        }
      this.$refs[formName].resetFields();
    },
    // addForm end
    handleAddMovie(movie){
      addMovie(movie).then(res=>{
        this.handleSuccess(res)
        this.resetForm('addForm')
      }).catch(err=> this.handleFiled(err))
    },
    handleDeleteMovie(movieId){
      deleteMovieById(movieId).then(res=>{
        this.handleSuccess(res)
      }).catch(err=> this.handleFiled(err))
    },
    handleUpdateMovie(movie){
      updateMovie(movie).then(res=>{
        this.handleSuccess(res)
        this.resetForm('addForm')
      }).catch(err=> this.handleFiled(err))
    },
    handleSuccess(res){
      this.modalForm.confirmLoading = false
      this.$notification['success']({
        message: '成功',
        description: `${res.data}`,
        duration: 4
      })
      this.getMovieData()
    },
    handleFiled(err){
      this.modalForm.confirmLoading = false
      console.log(err.message)
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).message || {}).message||err.message || '请求出现错误，请稍后再试',
        duration: 4
      })
    },
    // 地域类型根据Key来获取对应value
    getAreaValue(key){
      for (let item of this.allAreaItems){
        if (key===item.paramKey){
          return item.paramValue
        }
      }
      return "Unknown"
    },
    getTypeValue(key){
      for (let item of this.allTypeItems){
        if (key===item.paramKey){
          return item.paramValue
        }
      }
      return "Unknown"
    }
  },
  computed:{
    isDisable(){
      return this.formInline.movieNameLike==='';
    },
  }
}
</script>

<style>
.ant-upload.ant-upload-drag{
  height: 200px;
}
</style>
